package cn.hrc.controller;

import cn.hrc.dao.FileMapper;
import cn.hrc.dao.MyUserMapper;
import cn.hrc.entity.MyUser;
import cn.hrc.utils.PackJson;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/user")
public class UserInfoController {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    MyUserMapper myUserMapper;
    @Autowired
    PasswordEncoder passwordEncoder;
    @Autowired
    FileMapper fileMapper;
    @Autowired
    RedisTemplate redisTemplate;
    @GetMapping("/info")
    public String info() {
        // 获取当前登录用户
        Object who = SecurityContextHolder
                .getContext()
                .getAuthentication()
                .getPrincipal();
        if (who==null) {
            return PackJson.packJson(401, "没有登录或登录超时", "");
        }
        // 获取当前登录用户信息
        UserDetails usr = (UserDetails) who;
        String account = usr.getUsername();
        logger.info("当前登录用户："+account);
        // 查询用户信息
        QueryWrapper<MyUser> wrapper = new QueryWrapper<MyUser>()
                // select 是你要哪些字段
                .select("id","account","role","phone","nickname","vip","addr","img")
                //  查询条件【eq】 phone = #{phone}
                .eq("account", account);
        MyUser user = myUserMapper.selectOne(wrapper);
        logger.info("用户信息："+user);
        if (user == null) {
            return PackJson.packJson(401,"该用户不存在","");
        }
        return PackJson.packJson(200,"用户信息",user);
    }
    @GetMapping("/logout")
    public String logout(@RequestHeader("Authorization") String token) {
        logger.info("退出登录 删除 Redis 的token");
        //按到前段传过来的token
        System.out.println("token："+token);
        //切割token
        String[] split = token.split(" ");//
        token = split[1];
        System.out.println(token);
        //删除redis的token  .getOperations()获取redisTemplate的Operations对象
        redisTemplate.opsForValue().getOperations().delete("token:"+token);
        logger.info("退出登录 删除 Redis 的token 成功");
        return PackJson.packJson(200,"退出成功","");
    }
}
